﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LitJson;
using WAD.Client2.WXPay;
using WAD.DAL;
using WAD.Model.WeiXin;
using WAD.WEB.AppCode;
namespace WAD.Client2.Ajax
{
    /// <summary>
    /// WxJsApiAccessToken 的摘要说明
    /// </summary>
    public class WxJsApiAccessToken : AjaxBase
    {

        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "get": this.Get(); break;
            }
        }
        /// <summary>
        /// 获取微信预支付订单号
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Get()
        {

            var token = DAOWxJsApi.Get();
            if (string.IsNullOrEmpty(token.Access_Token) || token.Token_Expire < DateTime.Now)
            {
                //刷新accesstoken
                token = new JsApiAccessToken();
                string url =
                   $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={WxPayConfig.APPID}&secret={WxPayConfig.APPSECRET}";
                var result = HttpService.Get(url);
                Log.Debug(this.GetType().ToString(), "client_credential response : " + result);
                var jd = JsonMapper.ToObject(result);
                token.AppId = WxPayConfig.APPID;
                token.Access_Token = (string)jd["access_token"];
                token.Token_Expire = DateTime.Now.AddSeconds((int)jd["expires_in"]);
                DAOWxJsApi.Update(token);
            }
            if (token.Ticket_Expire < DateTime.Now || string.IsNullOrEmpty(token.JsApi_Ticket))
            {
                string url =
                    $"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={token.Access_Token}&type=jsapi";
                var result = HttpService.Get(url);
                Log.Debug(this.GetType().ToString(), "getticket response : " + result);
                var jd = JsonMapper.ToObject(result);
                token.JsApi_Ticket = (string)jd["ticket"];
                token.Ticket_Expire = DateTime.Now.AddSeconds((int)jd["expires_in"]);
                DAOWxJsApi.Update(token);
            }
            JsonResult(0, null, token);


        }
    }
}